<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>荒岛求生</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1E3A8A',
                        secondary: '#059669',
                        danger: '#DC2626',
                        warning: '#F59E0B',
                        info: '#0284C7',
                        light: '#F8FAFC',
                        dark: '#1E293B'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-shadow {
                text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            }
            .bg-noise {
                background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E");
                background-blend-mode: overlay;
                background-size: 200px;
            }
            .animate-pulse-slow {
                animation: pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite;
            }
        }
    </style>
</head>
<body class="font-inter bg-gradient-to-br from-dark to-primary min-h-screen text-light overflow-x-hidden bg-noise">
    <!-- 游戏容器 -->
    <div class="container mx-auto px-4 py-8 max-w-4xl">
        <!-- 游戏标题 -->
        <header class="mb-8 text-center">
            <h1 class="text-[clamp(2.5rem,5vw,4rem)] font-bold text-shadow text-warning mb-2 tracking-wider">
                荒岛求生
            </h1>
            <p class="text-[clamp(1rem,2vw,1.25rem)] text-light/80 max-w-2xl mx-auto">
                你被困在了一座荒岛上，必须运用智慧和勇气才能生存下去...
            </p>
        </header>

        <!-- 游戏区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
            <!-- 游戏提示 -->
            <div class="lg:col-span-3 text-center mb-4 animate-pulse-slow">
                <p class="text-warning text-lg font-bold">请点击探索海滩、丛林或礁石区开始游戏</p>
            </div>
            
            <!-- 左侧状态栏 -->
            <div class="lg:col-span-2">
                <div class="bg-dark/60 backdrop-blur-sm rounded-lg p-6 border border-primary/30 shadow-lg">
                    <div class="grid grid-cols-3 gap-4 mb-6">
                        <div class="bg-dark/80 rounded-lg p-3">
                            <div class="flex justify-between mb-1">
                                <span class="text-light/80">健康</span>
                                <span id="health" class="font-bold">100</span>
                            </div>
                            <div class="w-full bg-gray-700 rounded-full h-2">
                                <div id="health-bar" class="bg-danger h-2 rounded-full" style="width: 100%"></div>
                            </div>
                        </div>
                        <div class="bg-dark/80 rounded-lg p-3">
                            <div class="flex justify-between mb-1">
                                <span class="text-light/80">水分</span>
                                <span id="water" class="font-bold">100</span>
                            </div>
                            <div class="w-full bg-gray-700 rounded-full h-2">
                                <div id="water-bar" class="bg-info h-2 rounded-full" style="width: 100%"></div>
                            </div>
                        </div>
                        <div class="bg-dark/80 rounded-lg p-3">
                            <div class="flex justify-between mb-1">
                                <span class="text-light/80">食物</span>
                                <span id="food" class="font-bold">100</span>
                            </div>
                            <div class="w-full bg-gray-700 rounded-full h-2">
                                <div id="food-bar" class="bg-warning h-2 rounded-full" style="width: 100%"></div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-dark/80 rounded-lg p-4 mb-4">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-light/80">生存时间</span>
                            <span id="time" class="font-bold">0天0小时0分0秒</span>
                        </div>
                    </div>
                    
                    <div id="game-log" class="bg-dark/80 rounded-lg p-4 h-64 overflow-y-auto">
                        <!-- 游戏日志内容将在这里动态生成 -->
                    </div>
                </div>
            </div>
            
            <!-- 右侧行动栏 -->
            <div>
                <div class="bg-dark/60 backdrop-blur-sm rounded-lg p-6 border border-primary/30 shadow-lg h-[500px] flex flex-col">
                    <h2 class="text-xl font-bold mb-4 border-b border-primary/20 pb-2">你的行动</h2>
                    
                    <div class="space-y-3 overflow-y-auto flex-grow">
                        <button class="action-btn w-full py-3 px-4 bg-secondary/80 hover:bg-secondary rounded-lg transition-all duration-300 flex items-center justify-between" data-action="explore-beach" onclick="exploreArea('海滩')">
                            <span>探索海滩</span>
                            <i class="fa fa-search"></i>
                        </button>
                        
                        <button class="action-btn w-full py-3 px-4 bg-secondary/80 hover:bg-secondary rounded-lg transition-all duration-300 flex items-center justify-between" data-action="explore-jungle" onclick="exploreArea('丛林')">
                            <span>探索丛林</span>
                            <i class="fa fa-tree"></i>
                        </button>
                        
                        <button class="action-btn w-full py-3 px-4 bg-secondary/80 hover:bg-secondary rounded-lg transition-all duration-300 flex items-center justify-between" data-action="explore-reef" onclick="exploreArea('礁石区')">
                            <span>探索礁石区</span>
                            <i class="fa fa-life-ring"></i>
                        </button>
                        
                        <button class="action-btn w-full py-3 px-4 bg-info/80 hover:bg-info rounded-lg transition-all duration-300 flex items-center justify-between" data-action="build-shelter" onclick="buildShelter()">
                            <span>建造避难所 (进度: <span id="shelter-progress">0</span>%)</span>
                            <i class="fa fa-home"></i>
                        </button>
                        
                        <button class="action-btn w-full py-3 px-4 bg-warning/80 hover:bg-warning rounded-lg transition-all duration-300 flex items-center justify-between" data-action="find-water" onclick="startWaterIncrease()">
                            <span>寻找水源</span>
                            <i class="fa fa-tint"></i>
                        </button>
                        
                        <button class="action-btn w-full py-3 px-4 bg-warning/80 hover:bg-warning rounded-lg transition-all duration-300 flex items-center justify-between" data-action="find-food" onclick="if(Math.random() < 0.8) startFoodIncrease();">
                            <span>寻找食物</span>
                            <i class="fa fa-cutlery"></i>
                        </button>
                        
                        <button class="action-btn w-full py-3 px-4 bg-primary/80 hover:bg-primary rounded-lg transition-all duration-300 flex items-center justify-between" data-action="build-signal">
                            <span>建造求救信号</span>
                            <i class="fa fa-fire"></i>
                        </button>
                    </div>
                    
                    <div class="mt-4 pt-4 border-t border-primary/20">
                        <button id="inventory-btn" class="w-full py-2 px-4 bg-dark hover:bg-dark/80 rounded-lg transition-all duration-300 flex items-center justify-center">
                            <i class="fa fa-briefcase mr-2"></i> 查看物品
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 题目展示框架 -->
        <div id="question-modal" class="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center hidden">
            <div class="bg-dark rounded-xl p-6 max-w-md w-full border border-primary/50 shadow-2xl">
                <div class="text-center mb-4">
                    <h3 id="question-title" class="text-2xl font-bold mb-2"></h3>
                    <p id="question-content" class="text-lg"></p>
                </div>
                <div class="mt-4" id="question-input">
                    <input type="text" id="answer-input" class="w-full bg-dark/80 border border-primary/30 rounded-lg px-4 py-2 text-light focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="请输入答案...">
                </div>
                <div class="mt-6 flex space-x-3">
                    <button id="submit-answer" class="flex-1 py-2 px-4 bg-primary hover:bg-primary/80 rounded-lg transition-all duration-300">
                        提交
                    </button>
                    <button id="cancel-question" class="flex-1 py-2 px-4 bg-dark hover:bg-dark/80 rounded-lg transition-all duration-300 border border-primary/30">
                        取消
                    </button>
                </div>
            </div>
        </div>         

        <!-- 物品栏模态框 -->
        <div id="inventory-modal" class="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center hidden">
            <div class="bg-dark rounded-xl p-6 max-w-md w-full border border-primary/30 shadow-2xl transform transition-all duration-300 scale-95 opacity-0" id="modal-content">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-2xl font-bold">你的物品</h3>
                    <button id="close-inventory" class="text-light/70 hover:text-light">
                        <i class="fa fa-times text-xl"></i>
                    </button>
                </div>
                
                <div id="inventory-items" class="space-y-3 max-h-[400px] overflow-y-auto">
                    <div class="text-light/70 italic text-center py-8">
                        你还没有任何物品
                    </div>
                </div>
                
                <div class="mt-6">
                    <button id="close-inventory-btn" class="w-full py-3 px-4 bg-primary hover:bg-primary/80 rounded-lg transition-all duration-300">
                        关闭
                    </button>
                </div>
            </div>
        </div>

        <!-- 游戏结束模态框 -->
        <div id="game-over-modal" class="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center hidden">
            <div class="bg-dark rounded-xl p-6 max-w-md w-full border border-danger/50 shadow-2xl">
                <div class="text-center mb-6">
                    <i class="fa fa-skull text-5xl text-danger mb-3 animate-pulse-slow"></i>
                    <h3 id="game-over-title" class="text-3xl font-bold text-danger mb-2">游戏结束</h3>
                    <p id="game-over-message" class="text-light/80">你未能在荒岛上生存下来...</p>
                </div>
                
                <div class="space-y-3">
                    <div class="bg-dark/80 rounded-lg p-4">
                        <div class="flex justify-between">
                            <span class="text-light/80">生存天数</span>
                            <span id="days-survived" class="font-bold">0</span>
                        </div>
                        <div class="w-full bg-gray-700 rounded-full h-2 mt-2">
                            <div class="bg-danger h-2 rounded-full" style="width: 100%"></div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-6">
                    <button id="restart-game" class="w-full py-3 px-4 bg-primary hover:bg-primary/80 rounded-lg transition-all duration-300">
                        重新开始
                    </button>
                </div>
            </div>
        </div>

        <!-- 成功获救模态框 -->
        <div id="rescued-modal" class="fixed inset-0 bg-black/70 backdrop-blur-sm z-50 flex items-center justify-center hidden">
            <div class="bg-dark rounded-xl p-6 max-w-md w-full border border-secondary/50 shadow-2xl">
                <div class="text-center mb-4">
                    <i class="fa fa-helicopter text-5xl text-secondary mb-3"></i>
                    <h3 id="rescued-title" class="text-3xl font-bold text-secondary mb-2">成功获救</h3>
                    <p id="rescued-message" class="text-light/80">你成功发出了求救信号，救援队已经抵达！</p>
                </div>
                
                <div class="space-y-3">
                    <div class="bg-dark/80 rounded-lg p-4">
                        <div class="flex justify-between">
                            <span class="text-light/80">生存天数</span>
                            <span id="days-rescued" class="font-bold">0</span>
                        </div>
                        <div class="w-full bg-gray-700 rounded-full h-2 mt-2">
                            <div class="bg-secondary h-2 rounded-full" style="width: 100%"></div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-6">
                    <button id="play-again" class="w-full py-3 px-4 bg-primary hover:bg-primary/80 rounded-lg transition-all duration-300" onclick="initGame()">
                        再来一次
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 游戏状态
        const gameState = {
            health: 100,
            water: 100,
            food: 100,
            gameTime: 0,
            days: 0,
            inventory: [],
            collectedItems: [],
            requiredItems: ['漂流木', '塑料瓶', '香蕉', '椰子', '海藻', '螃蟹'],
            shelterProgress: 0,
            exploring: false,
            findingWater: false,
            findingFood: false,
            gameInterval: null
        };

        // 初始化游戏
        function initGame() {
            // 重置游戏状态
            gameState.health = 100;
            gameState.water = 100;
            gameState.food = 100;
            gameState.gameTime = 0;
            gameState.days = 0;
            gameState.inventory = [];
            gameState.collectedItems = [];
            gameState.shelterProgress = 0;
            gameState.exploring = false;
            gameState.findingWater = false;
            gameState.findingFood = false;
            gameState.lowFoodWarned = false;
            gameState.lowWaterWarned = false;
            document.getElementById('shelter-progress').textContent = '0';
            
            // 清除之前的游戏间隔
            if(gameState.gameInterval) {
                clearInterval(gameState.gameInterval);
                gameState.gameInterval = null;
            }
            
            gameStarted = false;
            
            // 初始化游戏日志
            document.getElementById('game-log').innerHTML = 
                '<p class="italic text-light/70">你在一片沙滩上醒来，头痛欲裂。环顾四周，发现自己被困在了一座荒岛上...</p>' +
                '<p class="text-light">你必须尽快找到水源和食物，否则生存的机会渺茫...</p>';
            
            // 隐藏所有模态框
            document.getElementById('game-over-modal').classList.add('hidden');
            document.getElementById('rescued-modal').classList.add('hidden');
            
            updateStatus();
        }
    
        // 游戏是否已开始
        let gameStarted = false;

        
        // 启动游戏
        function startGame() {
            if(!gameStarted) {
                initGame();
                if(gameState.gameInterval) {
                    clearInterval(gameState.gameInterval);
                }
                gameState.gameInterval = setInterval(updateStatus, 1000);
                gameStarted = true;
                
                // 添加到游戏日志
                const gameLog = document.getElementById('game-log');
                gameLog.innerHTML += '<p class="text-light">游戏已开始！生存时间开始计时...</p>';
            }
        }
        
        // 确保游戏不会自动开始
        document.addEventListener('DOMContentLoaded', function() {
            gameStarted = false;
        });

        // 更新状态显示
        function updateStatus()
        {
            document.getElementById('health').textContent = gameState.health;
            document.getElementById('water').textContent = gameState.water;
            document.getElementById('food').textContent = gameState.food;
            document.getElementById('health-bar').style.width = `${gameState.health}%`;
            document.getElementById('water-bar').style.width = `${gameState.water}%`;
            document.getElementById('food-bar').style.width = `${gameState.food}%`;
            
            // 探索时持续减少体力和水分
            if (gameState.exploring) {
                if(gameState.food<=80||gameState.water<=80){
                    gameState.health -= 2;
                    if(gameState.food<=80 && !gameState.lowFoodWarned){
                        alert('警告：食物值低于80，请尽快寻找食物！');
                        gameState.lowFoodWarned = true;
                    }
                    if(gameState.water<=80 && !gameState.lowWaterWarned){
                        alert('警告：你需要尽快寻找水源！');
                        gameState.lowWaterWarned = true;
                    }
                }
                gameState.food -= 1;
                gameState.water -= 1;
                
               
            
            // 时间递减逻辑（仅在游戏开始后计时）
            if(gameStarted) {
                gameState.gameTime++;
            }
            
            // 更新游戏时间显示
            const days = Math.floor(gameState.gameTime / 86400);
            const hours = Math.floor((gameState.gameTime % 86400) / 3600);
            const minutes = Math.floor((gameState.gameTime % 3600) / 60);
            const seconds = gameState.gameTime % 60;
            document.getElementById('time').textContent = `${days}天${hours}小时${minutes}分${seconds}秒`;
            
            // 检查游戏结束条件
            if(gameState.gameTime >= 600) {
                document.getElementById('rescued-modal').classList.remove('hidden');
                document.getElementById('days-rescued').textContent = gameState.days;
                clearInterval(gameState.gameInterval);
            } else if(gameState.food <= 0) {
                document.getElementById('game-over-modal').classList.remove('hidden');
                document.getElementById('game-over-title').textContent = '饿死了';
                document.getElementById('game-over-message').textContent = '你因为缺乏食物而饿死了...';
                document.getElementById('days-survived').textContent = gameState.days;
                clearInterval(gameState.gameInterval);
            } else if(gameState.water <= 0) {
                document.getElementById('game-over-modal').classList.remove('hidden');
                document.getElementById('game-over-title').textContent = '渴死了';
                document.getElementById('game-over-message').textContent = '你因为缺乏水分而渴死了...';
                document.getElementById('days-survived').textContent = gameState.days;
                clearInterval(gameState.gameInterval);
            } else if(gameState.health <= 0) {
                document.getElementById('game-over-modal').classList.remove('hidden');
                document.getElementById('game-over-title').textContent = '累死了';
                document.getElementById('game-over-message').textContent = '你因为体力耗尽而累死了...';
                document.getElementById('days-survived').textContent = gameState.days;
                clearInterval(gameState.gameInterval);
            }} 
            
        }

        // 物品效果
        const itemEffects = {
            '贝壳': { water: 5, food: 0, health: 0 },
            '漂流木': { water: 0, food: 0, health: 0 },
            '塑料瓶': { water: 10, food: 0, health: 0 },
            '香蕉': { water: 5, food: 15, health: 5 },
            '椰子': { water: 20, food: 10, health: 5 },
            '蘑菇': { water: 0, food: 10, health: -5 },
            '海藻': { water: 5, food: 5, health: 0 },
            '螃蟹': { water: 0, food: 20, health: 0 },
            '海星': { water: 0, food: 5, health: 0 },
            '纯净水': { water: 50, food: 0, health: 0 },
            '牛肉': { water: 0, food: 50, health: 0 }
        };
        
        // 添加物品到物品栏
        function addToInventory(itemName, quantity = 1) {
            // 确保物品栏数组已初始化
            if (!gameState.inventory) {
                gameState.inventory = [];
            }
            
            // 查找现有物品
            const existingItem = gameState.inventory.find(item => item && item.name === itemName);
            
            if (existingItem) {
                existingItem.quantity += quantity;
            } else {
                // 添加新物品
                gameState.inventory.push({ 
                    name: itemName, 
                    quantity: quantity,
                    effects: itemEffects[itemName]
                });
            }
            
            // 强制更新UI
            updateInventory();
            
            // 添加到游戏日志
            const log = document.getElementById('game-log');
            if(itemName === '纯净水') {
                log.innerHTML += '<p class="text-info">你找到了纯净水，可以补充大量水分！</p>';
            } else if(itemName === '牛肉') {
                log.innerHTML += '<p class="text-info">你找到了食物，可以补充大量体力！</p>';
            }
            log.scrollTop = log.scrollHeight;
            
            // 调试日志
            console.log('Added item:', itemName, 'Quantity:', quantity);
            console.log('Current inventory:', gameState.inventory);
        }
        
        // 使用物品
        function useItem(item) {
            if (!gameState.inventory.some(i => i.name === item)) return;
            
            const effect = itemEffects[item];
            if (effect.water > 0) gameState.water = Math.min(100, gameState.water + effect.water);
            if (effect.food > 0) gameState.food = Math.min(100, gameState.food + effect.food);
            if (effect.health > 0) gameState.health = Math.min(100, gameState.health + effect.health);
            
            // 从物品栏移除
            const itemIndex = gameState.inventory.findIndex(i => i.name === item);
            if (itemIndex !== -1) {
                if (gameState.inventory[itemIndex].quantity > 1) {
                    gameState.inventory[itemIndex].quantity -= 1;
                } else {
                    gameState.inventory.splice(itemIndex, 1);
                }
            }
            
            // 更新日志
            const log = document.getElementById('game-log');
            log.innerHTML += `<p class="text-info">你使用了${item}，${effect.water > 0 ? '水分+' + effect.water : ''}${effect.food > 0 ? '食物+' + effect.food : ''}${effect.health > 0 ? '体力+' + effect.health : ''}</p>`;
            log.scrollTop = log.scrollHeight;
            
            updateInventory();
            updateStatus();
        }
        
        // 探索区域函数
        function exploreArea(area) {
            // 如果游戏未开始，先启动游戏
            if(!gameStarted) {
                startGame();
            }
            
            const items = {
        '海滩': ['贝壳', '漂流木', '塑料瓶'],
        '丛林': ['香蕉', '椰子', '蘑菇'],
        '礁石区': ['海藻', '螃蟹', '海星']
        };
    
        const foundItems = [];
        const randomCount = Math.floor(Math.random() * 2) + 1; // 1-2个物品
    
        for (let i = 0; i < randomCount; i++) {
            const randomIndex = Math.floor(Math.random() * items[area].length);
            const item = items[area][randomIndex];
            foundItems.push(item);
            addToInventory(item); // 使用统一函数添加物品
            }
            
            // 更新游戏日志
            const log = document.getElementById('game-log');
            let message = `<p class="text-light">你在${area}探索，发现了：${foundItems.join('、')}</p>`;
            log.innerHTML += message;
            log.scrollTop = log.scrollHeight;
            
            // 更新物品栏显示
            updateInventory();
            updateStatus();
        }
        
        // 更新物品栏显示
        // 更新物品栏显示
function updateInventory() {
    const inventoryItems = document.getElementById('inventory-items');
    inventoryItems.innerHTML = '';
    
    // 显示人物状态
    const statusElement = document.createElement('div');
    statusElement.className = 'bg-dark/80 rounded-lg p-4 mb-4';
    statusElement.innerHTML = `
        <div class="grid grid-cols-3 gap-2">
            <div>生命值: ${gameState.health}%</div>
            <div>水分: ${gameState.water}%</div>
            <div>食物: ${gameState.food}%</div>
        </div>
        <div class="mt-2">避难所进度: ${gameState.shelterProgress}%</div>
    `;
    inventoryItems.appendChild(statusElement);
    
    if (gameState.inventory.length === 0) {
        inventoryItems.innerHTML += '<div class="text-light/70 italic text-center py-8">你还没有任何物品</div>';
        return;
    }
    
    // 显示物品
    gameState.inventory.forEach(item => {
        const itemElement = document.createElement('div');
        itemElement.className = 'bg-dark/80 rounded-lg p-3 flex justify-between items-center';
        
        // 添加物品使用说明
        let description = '';
        let buildButton = '';
        
        // 特殊建造材料
        if (item.name === '贝壳' || item.name === '塑料瓶' || item.name === '漂流木') {
            const progressValue = item.name === '漂流木' ? 15 : 5;
            description = `用于建造避难所 (+${progressValue}%)`;
            buildButton = `<button onclick="useItemForBuilding('${item.name}')" class="bg-green-500 hover:bg-green-600 text-white px-2 py-1 rounded text-sm ml-2">建造</button>`;
        }
        // 其他物品描述
        if(item.name === '塑料瓶') description = '使用后恢复10%水分';
                else if(item.name === '椰子') description = '使用后恢复15%食物';
                else if(item.name === '香蕉') description = '使用后水分恢复5%食物恢复15%体力恢复5%';
                else if(item.name === '海藻') description = '使用后恢复10%水分';
                else if(item.name === '螃蟹') description = '使用后恢复10%食物';
                else if(item.name === '海星') description = '使用后恢复10%食物';
                else if(item.name === '蘑菇') description = '使用后恢复15%食物';
                else if(item.name === '漂流木') description = '用于建造避难所';
                else if(item.name === '贝壳') description = '装饰品，无实际用途';
                else if(item.name === '纯净水') description = '使用后恢复50%水分';
                else if(item.name === '牛肉') description = '使用后恢复50%食物';
        
        itemElement.innerHTML = `
            <div>
                <span class="text-light">${item.name}</span>
                <div class="text-xs text-light/50">${description}</div>
            </div>
            <div class="flex items-center">
                <span class="text-light/70">x${item.quantity}</span>
                ${item.effects ? `<button onclick="useItem('${item.name}')" class="bg-blue-500 hover:bg-blue-600 text-white px-2 py-1 rounded text-sm ml-2">使用</button>` : ''}
                ${buildButton}
            </div>
        `;
        inventoryItems.appendChild(itemElement);
    });
}
        // 使用物品建造避难所
function useItemForBuilding(itemName) {
    let progressGained = 0;
    
    // 确定每种材料提供的进度
    switch(itemName) {
        case '漂流木':
            progressGained = 15;
            break;
        case '贝壳':
        case '塑料瓶':
            progressGained = 5;
            break;
    }
    
    // 从物品栏移除该物品
    const itemIndex = gameState.inventory.findIndex(item => item.name === itemName);
    if (itemIndex !== -1) {
        if (gameState.inventory[itemIndex].quantity > 1) {
            gameState.inventory[itemIndex].quantity -= 1;
        } else {
            gameState.inventory.splice(itemIndex, 1);
        }
    }
    
    // 增加避难所进度
    gameState.shelterProgress = Math.min(100, gameState.shelterProgress + progressGained);
    document.getElementById('shelter-progress').textContent = gameState.shelterProgress;
    
    // 更新日志
    const log = document.getElementById('game-log');
    log.innerHTML += `<p class="text-info">你使用了${itemName}建造避难所，进度增加${progressGained}%，当前进度: ${gameState.shelterProgress}%</p>`;
    log.scrollTop = log.scrollHeight;
    
    // 更新物品栏
    updateInventory();
    
    // 检查是否完成
    if (gameState.shelterProgress >= 100) {
        document.getElementById('rescued-modal').classList.remove('hidden');
        document.getElementById('days-rescued').textContent = gameState.days;
        document.getElementById('rescued-title').textContent = '避难所完成';
        document.getElementById('rescued-message').textContent = '你成功建造了避难所，现在可以安全生存了！';
    }
}
       // 建造避难所
function buildShelter() {
    let materialsUsed = [];
    let progressGained = 0;
    
    // 检查贝壳
    const shellIndex = gameState.inventory.findIndex(item => item.name === '贝壳');
    if (shellIndex !== -1) {
        // 从物品栏移除贝壳
        if (gameState.inventory[shellIndex].quantity > 1) {
            gameState.inventory[shellIndex].quantity -= 1;
        } else {
            gameState.inventory.splice(shellIndex, 1);
        }
        progressGained += 5;
        materialsUsed.push('贝壳');
    }
    
    // 检查塑料瓶
    const bottleIndex = gameState.inventory.findIndex(item => item.name === '塑料瓶');
    if (bottleIndex !== -1) {
        // 从物品栏移除塑料瓶
        if (gameState.inventory[bottleIndex].quantity > 1) {
            gameState.inventory[bottleIndex].quantity -= 1;
        } else {
            gameState.inventory.splice(bottleIndex, 1);
        }
        progressGained += 5;
        materialsUsed.push('塑料瓶');
    }
    
    // 检查漂流木
    const woodIndex = gameState.inventory.findIndex(item => item.name === '漂流木');
    if (woodIndex !== -1) {
        // 从物品栏移除漂流木
        if (gameState.inventory[woodIndex].quantity > 1) {
            gameState.inventory[woodIndex].quantity -= 1;
        } else {
            gameState.inventory.splice(woodIndex, 1);
        }
        progressGained += 15;
        materialsUsed.push('漂流木');
    }
    
    if (materialsUsed.length > 0) {
        // 增加避难所进度
        gameState.shelterProgress = Math.min(100, gameState.shelterProgress + progressGained);
        document.getElementById('shelter-progress').textContent = gameState.shelterProgress;
        
        // 更新日志
        const log = document.getElementById('game-log');
        log.innerHTML += `<p class="text-info">你使用了${materialsUsed.join('、')}建造避难所，进度增加${progressGained}%，当前进度: ${gameState.shelterProgress}%</p>`;
        log.scrollTop = log.scrollHeight;
        
        // 更新物品栏
        updateInventory();
        
        // 检查是否完成
        if (gameState.shelterProgress >= 100) {
            document.getElementById('rescued-modal').classList.remove('hidden');
            document.getElementById('days-rescued').textContent = gameState.days;
            document.getElementById('rescued-title').textContent = '避难所完成';
            document.getElementById('rescued-message').textContent = '你成功建造了避难所，现在可以安全生存了！';
        }
    } else {
        alert('你需要贝壳、塑料瓶或漂流木才能建造避难所！\n贝壳/塑料瓶: +5%进度\n漂流木: +15%进度');
    }
}
        
        // 检查胜利条件
        function checkWinCondition() {
            if (gameState.requiredItems.every(item => gameState.collectedItems.includes(item))) {
                document.getElementById('rescued-modal').classList.remove('hidden');
                document.getElementById('days-rescued').textContent = gameState.days;
            }
        }

        // 调用DeepSeek API
        async function callDeepSeekAPI(action, currentLevel) {
            // 处理寻找水源的特殊逻辑
            if (action === 'find-water') {
                const operators = ['+', '-', '*', '/'];
                const operator = operators[Math.floor(Math.random() * operators.length)];
                let num1 = Math.floor(Math.random() * 20) + 1;
                let num2 = Math.floor(Math.random() * 20) + 1;
                
                // 确保除法结果为整数
                if (operator === '/') {
                    num1 = num2 * (Math.floor(Math.random() * 5) + 1);
                }
                
                const expression = `${num1} ${operator} ${num2}`;
                const answer = Math.round(eval(expression));
                
                const userAnswer = prompt(`回答这个数学题来寻找水源: ${expression} = ?`);
                
                if (parseInt(userAnswer) === answer) {
                    addToInventory('纯净水', 1);
                    return '回答正确！你成功找到了水源！获得了一瓶纯净水';
                } else {
                    return `回答错误！正确答案是${answer}。继续寻找水源吧...`;
                }
            }
            
            if (action === 'find-food'){
                const words = [
                    {word: 'accomplish', hint: '完成', pattern: 'a______sh'},
                    {word: 'brilliant', hint: '辉煌的', pattern: 'b______t'},
                    {word: 'challenge', hint: '挑战', pattern: 'c______e'},
                    {word: 'determine', hint: '决定', pattern: 'd______e'},
                    {word: 'essential', hint: '必要的', pattern: 'e______l'}
                ];
                const randomWordObj = words[Math.floor(Math.random() * words.length)];
                
                const userAnswer = prompt(`请拼写这个单词(中文意思:${randomWordObj.hint}): ${randomWordObj.pattern}`);
                
                if (userAnswer.toLowerCase() === randomWordObj.word) {
                    gameState.food += 50;
                    addToInventory('牛肉', 1);
                    return '拼写正确！你成功找到了食物！获得了一块牛肉';
                } else {
                    return `拼写错误！正确答案是${randomWordObj.word}。你没有找到食物，继续寻找吧...`;
                }
            }
            
            let systemContent = '';
            
            switch(action) {
                case 'explore-beach':
                    systemContent = '你现在是一个荒岛求生者，你现在要生成探索海滩可能找到的物品情况';
                    break;
                case 'explore-jungle':
                    systemContent = '你现在是一个荒岛求生者，你现在要生成探索丛林可能遇到的危险和资源';
                    break;
                case 'explore-reef':
                    systemContent = '你现在是一个荒岛求生者，你现在要生成探索礁石区可能发现的海洋资源';
                    break;
                case 'build-shelter':
                    systemContent = '你现在是一个荒岛求生者，你现在要描述建造避难所的进展和困难';
                    break;
                case 'build-signal':
                    systemContent = '你现在是一个荒岛求生者，你现在要描述建造求救信号的过程和效果';
                    break;
                default:
                    systemContent = '你现在是一个荒岛求生者，你现在要描述当前的生存状况';
            }
            
            const payload = {
                model: 'deepseek-chat',
                messages: [
                    {
                        role: 'system',
                        content: systemContent
                    },
                    {
                        role: 'user',
                        content: `生成第${currentLevel}次${action}的遭遇，要求:\n1.包含有趣的可能性\n2.有引人入胜的背景故事\n3.字数大概100字`
                    }
                ]
            };

            try {
                const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer sk-e48e5c701d1841239c968e5fbf28f4a6'
                    },
                    body: JSON.stringify(payload)
                });

                const data = await response.json();
                return data.choices[0].message.content;
            } catch (error) {
                console.error('API调用失败:', error);
                return `在${action}时遇到了一些问题...`;
            }
        }

        // 启动游戏
        startGame();
        
        // 重新开始游戏
        document.getElementById('restart-game').addEventListener('click', () => {
            initGame();
            document.getElementById('game-over-modal').classList.add('hidden');
        });

        // 物品栏按钮事件
        document.getElementById('inventory-btn').addEventListener('click', () => {
            updateInventory();
            document.getElementById('inventory-modal').classList.remove('hidden');
            setTimeout(() => {
                document.getElementById('modal-content').classList.remove('scale-95', 'opacity-0');
            }, 10);
        });

        // 关闭物品栏
        document.getElementById('close-inventory').addEventListener('click', () => {
            document.getElementById('modal-content').classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                document.getElementById('inventory-modal').classList.add('hidden');
            }, 300);
        });

        document.getElementById('close-inventory-btn').addEventListener('click', () => {
            document.getElementById('modal-content').classList.add('scale-95', 'opacity-0');
            setTimeout(() => {
                document.getElementById('inventory-modal').classList.add('hidden');
            }, 300);
        });

        // 定义动作对应的物品
        const actionItems = {
            'beach': '贝壳',
            'jungle': '草药',
            'reef': '珊瑚',
            'find-water': '水瓶',
            'find-food': '食物'
        };
        
        // 事件处理
        document.querySelectorAll('.action-btn').forEach(btn => {
            btn.addEventListener('click', async function() {
                const action = this.dataset.action;
                // 开始持续减少体力
                gameState.exploring = true;
                
                const currentLevel = gameState.inventory.filter(item => item === actionItems[action]).length + 1;
                const result = await callDeepSeekAPI(action, currentLevel);
                
                // 添加到游戏日志
                const log = document.getElementById('game-log');
                const entry = document.createElement('p');
                entry.textContent = result;
                log.appendChild(entry);
                
                // 收集物品
                if(actionItems[action]) {
                    gameState.collectedItems.push(actionItems[action]);
                    checkWinCondition();
                }
                
                updateStatus();
            });
        });
    </script>
</body>
</html>